import React, { FC, MouseEvent } from "react"
import styles from "./EditCanvas.module.scss"
import useGetComponentInfo from "../../../../hooks/useGetComponentInfo"
import { getComponentConfigByType } from "../../../../components/QuestionComponents"
import { Spin } from "antd"
import { changeSelectedId, ComponentInfoType, moveComponent } from "../../../../store/componentsReducer"
import { useDispatch } from "react-redux"
import classNames from "classnames"
import useBindCanvasKeyPress from "../../../../hooks/useBindCanvasKeyPress"

import SortableContainer from "../../../../components/DragSortable/SortableContainer"
import SortableItem from "../../../../components/DragSortable/SortableItem"

type PropsType = {
    loading: boolean
}

// 在组件外定义，组件每次渲染时不会每次都定义
// 获取组件
function genComponent(componentInfo: ComponentInfoType) {
    const { type, props } = componentInfo
    // 获取组件类型
    const componentConfig = getComponentConfigByType(type)

    // 使用双等号，三等号只能检查=null的情况
    if (componentConfig == null) return null

    const { Component } = componentConfig
    return <Component {...props} />
}

const EditCanvas: FC<PropsType> = (props: PropsType) => {
    const { loading } = props
    const { componentList, selectedId } = useGetComponentInfo()

    const dispatch = useDispatch()

    function handleClick(event: MouseEvent, id: string) {
        // 阻止事件冒泡
        event.stopPropagation()
        dispatch(changeSelectedId(id))
    }

    // 添加快捷键操作
    useBindCanvasKeyPress()

    if (loading) {
        // 如果还在加载中  就显示一个正在加载的组件（页面优化）
        return (
            <div style={{ textAlign: "center", marginTop: "24px" }}>
                <Spin />
            </div>
        )
    }

    // SortableContainer 组件的items属性，需要每个item都有id属性
    const componentListWithId = componentList.map(c => {
        return { ...c, id: c.fe_id }
    })

    // 拖拽排序结束
    function handleDragEnd(oldIndex: number, newIndex: number) {
        // console.log("handleDragEnd", oldIndex, newIndex)
        dispatch(moveComponent({ oldIndex, newIndex }))
    }

    return (
        <div className={styles.canvas}>
            <SortableContainer items={componentListWithId} onDragEnd={handleDragEnd}>
                {componentList
                    .filter(component => !component.isHidden)
                    .map(component => {
                        const { fe_id, isLocked } = component

                        // 拼接class name
                        const wrapperDefaultClaaName = styles["component-wrapper"]
                        const selectedClassName = styles.selected
                        const lockedClassName = styles.locked
                        const wrapperClassName = classNames({
                            // 动态变量名
                            [wrapperDefaultClaaName]: true,
                            [selectedClassName]: fe_id === selectedId,
                            [lockedClassName]: isLocked
                        })

                        return (
                            <SortableItem key={fe_id} id={fe_id}>
                                <div className={wrapperClassName} onClick={e => handleClick(e, fe_id)}>
                                    <div className={styles.component}>{genComponent(component)}</div>
                                </div>
                            </SortableItem>
                        )
                    })}
                {/* <div className={styles["component-wrapper"]}>
                <div className={styles.component} >
                    <QuestionTitle />
                </div>
            </div>
            <div className={styles["component-wrapper"]}>
                <div className={styles.component}>
                    <QuestionInput />
                </div>
            </div> */}
            </SortableContainer>
        </div>
    )
}

export default EditCanvas
